package com.zmn.oms.admin.controller.part;

import com.google.common.collect.Maps;
import com.zmn.base.product.dubbo.interfaces.product.foreign.ProductBusinessLineForeignListRemoteService;
import com.zmn.common.dto.LayuiTableResponseDTO;
import com.zmn.common.dto2.Option;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MoneyUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.office.excel.ExportExcel;
import com.zmn.oms.admin.controller.work.list.WorkListTabBaseController;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.model.entity.part.OrderPartEsQuery;
import com.zmn.oms.model.vo.part.ZsOrderPartVO;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderPartBService;
import com.zmn.oms.zmn.business.interfaces.part.ZsOrderPartQueryBService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Objects;

/**
 * 类描述：工单配件
 *
 * @author yangjiangming
 * @date 2018/11/26 9:30
 */
@Controller
@RequestMapping("/order_part")
public class PartListController extends WorkListTabBaseController {

    @Autowired
    private ZsOrderPartQueryBService zsOrderPartQueryBService;
    @Autowired
    ZsOrderPartBService zsOrderPartBService;
    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ProductBusinessLineForeignListRemoteService productBusinessLineListRemoteService;

    @RequiresPermissions("/zs/order_part/list.action")
    @GetMapping("list")
    public ModelAndView list(ModelAndView mv) {
        mv.setViewName("part/list");
        // 是否
        mv.addObject("yesOrNo", OrderConsts.getYesOrNoObj());
        // 城市集合
        mv.addObject("cityList", super.getCityListByDept());
        // 工程师 see com.zmn.oms.admin.controller.common.StaffController.masterList
        // 配件 see com.zmn.oms.admin.controller.common.PartSkuController.list
        // 工单配件类型
        mv.addObject("partTypeList", OrderConsts.getPartTypeList());
        // 配件一级分类
        mv.addObject("partCategOneList", super.categOnelist());
        // 配件二级分类 see com.zmn.oms.admin.controller.common.PartSkuController.categOnelist
        // 报销状态
        mv.addObject("partReimburseStatusList", OrderConsts.getOrderPartReimburseStatusList());

        // 默认30天
        mv.addObject("startTime", DateUtil.toString(DateUtil.addDays(DateUtil.getNow(), -30), "yyyy-MM-dd"));
        mv.addObject("endTime", DateUtil.toString(DateUtil.getNow(), "yyyy-MM-dd"));

        super.setDayLimit(mv);
        super.setDefaultModelAndView(mv);
        // 获取配件转换
        //Map<Integer, ZsPartUnitConversionVO> partUnitConversion = zsOrderPartBService.getPartUnitConversion();
        //mv.addObject("conversionMap", partUnitConversion);
        return mv;
    }

    @RequiresPermissions("/zs/order_part/list.action")
    @PostMapping("/ajax/list")
    @ResponseBody
    public ResultDTO ajaxList(@RequestBody OrderPartEsQuery query) {

        // 设置下单平台
        query.setPlat(null);

        List<ZsOrderPartVO> voList = zsOrderPartQueryBService.listPageOrderPartByQuery(query);
        LayuiTableResponseDTO data = LayuiTableResponseDTO.success(query.getTotalCount(), voList);
        return ResultDTO.success(data);
    }

    @RequiresPermissions("/zs/order_part/list.action")
    @GetMapping(value = "/exportexcel")
    public void exportExcel(OrderPartEsQuery query, HttpServletResponse response)
            throws Exception {

        // 设置下单平台
        query.setPlat(null);

        // 导出最多五千条
        query.setPageSize(10000);
        List<ZsOrderPartVO> voList = zsOrderPartQueryBService.exportListOrderPartByQuery(query);

        //Map<Integer, ZsPartUnitConversionVO> partUnitConversion = zsOrderPartBService.getPartUnitConversion();

        LinkedHashMap<String, String> fieldMap = Maps.newLinkedHashMap();
        fieldMap.put("orderId", "工单号");
        fieldMap.put("bizLineCallback", "业务线");
        fieldMap.put("manageCompanyName", "服务商");
        fieldMap.put("showProductName", "前台服务产品");
        fieldMap.put("totalAmountCallback", "订单收入");
        fieldMap.put("masterName", "工程师");
        fieldMap.put("cityName", "城市");
        fieldMap.put("partTypeName", "配件类型");
        fieldMap.put("categOneName", "一级分类");
        fieldMap.put("categName", "二级分类");
        fieldMap.put("partName", "配件");
        fieldMap.put("numberCallBack", "使用数量");
        fieldMap.put("unitCallBack", "单位");
        fieldMap.put("amountCallBack", "金额");
        fieldMap.put("reimburseStatusName", "报销状态");
        fieldMap.put("reimburseTime", "报销时间");
        fieldMap.put("accountTime", "算账时间");
        ExportExcel<ZsOrderPartVO> excel = new ExportExcel<>(voList, fieldMap, true);
        // 业务线名称缓存
        HashMap<Integer, String> bizLineMap = Maps.newHashMap();
        excel.setCallback((fieldName, entity) -> {
            //String partId = entity.getPartId();
            switch (fieldName) {
                case "amountCallBack":
                    return  MoneyUtil.parseToYuanEndWithUnit(entity.getAmount());
                case "numberCallBack":
                    return entity.getNumber().toString();
                    /*if (partUnitConversion.containsKey(partId)) {
                        ZsPartUnitConversionVO conversion = partUnitConversion.get(partId);
                        return MathUtil.div(entity.getNumber(), conversion.getScale(), 2);
                    } else {
                        return entity.getNumber();
                    }*/
                case "unitCallBack":
                    return entity.getUnit();
                    /*if (partUnitConversion.containsKey(partId)) {
                        ZsPartUnitConversionVO conversion = partUnitConversion.get(partId);
                        return conversion.getUnit();
                    } else {
                        return entity.getUnit();
                    }*/
                case "totalAmountCallback":
                    return MoneyUtil.parseToYuanStr(entity.getTotalAmount());
                case "bizLineCallback":
                    if (NumberUtil.isNotNullOrZero(entity.getBizLine())) {
                        // 业务线处理
                        String bizLineName = bizLineMap.get(entity.getBizLine());
                        if (Objects.nonNull(bizLineName)) {
                            return bizLineName;
                        }

                        ResponseDTO<Option<Integer>> nameVtRsp = productBusinessLineListRemoteService.getOptionNameById(entity.getBizLine());
                        Option<Integer> vtDTO = nameVtRsp.getData();
                        if (Objects.nonNull(vtDTO)) {
                            bizLineMap.put(entity.getBizLine(), vtDTO.getLabel());
                            return vtDTO.getLabel();
                        }
                    }
                default:
                    break;
            }
            return null;
        });
        excel.exportExcel(response, "工单配件");
    }
}
